//
//  MGTextView.m
//  Express
//
//  Created by lhongl on 2025/9/26.
//  Copyright © 2025 QM. All rights reserved.
//

#import "MGTextView.h"
static CGFloat const offset = 7;

@interface MGTextView ()
///
@property (nonatomic, copy) NSString  *tempPlaceholder;

@end
@implementation MGTextView

- (instancetype)init{
    if (self = [super init]) {
        [self setDefaultValue];
        [self addNotification];
    }
    return self;
}

#pragma mark - 设置默认值
- (void)setDefaultValue{
       self.textContainer.lineFragmentPadding = 0;
       self.scrollEnabled = NO;
       self.limitLength = 0;
       _placeholderAlignment = NSTextAlignmentLeft;
       _placeholderFont = [UIFont systemFontOfSize:14];
       _placeholderColor = [UIColor lightGrayColor];
}

#pragma mark - 添加通知
- (void)addNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
}

#pragma mark - 输入框发生变化
- (void)textDidChange{
    [self setTextViewDraw];
    if (self.limitLength != 0 && self.text.length > 0) {
        [self handelTextFieldForLengthLimit];
    }
    if ([self.customDelegate respondsToSelector:@selector(textDidChangeView:text:)]) {
        [self.customDelegate textDidChangeView:self text:self.text];
    }
}

#pragma mark - 设置文字变化
- (void)setTextViewDraw{
    if (self.text.length <= 0) {
        self.tempPlaceholder = self.placeholder;
        [self setNeedsDisplay];
        return;
    }
    if (self.tempPlaceholder.length == 0) {
        return;
    }
    self.tempPlaceholder = @"";
    [self setNeedsDisplay];
}

#pragma mark - 内容高度
- (void)drawRect:(CGRect)rect{
    if (self.text.length < 1 && self.tempPlaceholder.length != 0) {
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
        style.alignment =  self.placeholderAlignment;
        NSDictionary *attributes =@{NSFontAttributeName: self.placeholderFont,
                                        NSForegroundColorAttributeName:self.placeholderColor,
                                        NSParagraphStyleAttributeName: style
                                        };
       CGRect showFrame = CGRectMake(0, 0, 0, 0);
        CGFloat width = self.frame.size.width;
        CGFloat height = self.frame.size.height;
        CGSize size = [self textSizeWithString:self.tempPlaceholder width:width - offset*2 font:self.placeholderFont];
        CGFloat y = offset;
        if (self.placeholderLocation == PlaceholderLocationTop) {
            y = offset;
        }else if (self.placeholderLocation == PlaceholderLocationMiddle) {
            y = (height - size.height)/2;
        }else if (self.placeholderLocation == PlaceholderLocationBottom) {
            y = height - size.height - offset;
        }
        showFrame = CGRectMake(0, y, width, size.height + 5);
        [self.tempPlaceholder drawInRect:showFrame withAttributes:attributes];
    }
}

#pragma mark - 输入看文字限制
- (void)handelTextFieldForLengthLimit{
    NSString *tempStr = [self.text copy];
    NSInteger length = self.limitLength;
    if (!length) return;
    NSString *lang = [self.textInputMode primaryLanguage];
    if ([lang isEqualToString:@"zh-Hans"]) {
        UITextRange *selectedRange = [self markedTextRange];
        UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];
        if (!position) {
            if (tempStr.length >= length) {
                NSString *strNew = [NSString stringWithString:tempStr];
                strNew = [strNew substringToIndex:length];
                [self setText:strNew];
            }
        }
    }else{
        if ([tempStr length] >= length) {
            NSString *strNew = [NSString stringWithString:tempStr];
            strNew = [strNew substringToIndex:length];
            [self setText:strNew];
        }
    }
    if ([self.customDelegate respondsToSelector:@selector(textView:count:limitLength:)]) {
        [self.customDelegate textView:self count:self.text.length limitLength:self.limitLength];
    }
}


/// 文字大小
/// - Parameters:
///   - string: 内容
///   - width: 宽度
///   - font: 字体
- (CGSize)textSizeWithString:(NSString *)string width:(CGFloat)width font:(UIFont *)font{
    NSDictionary *dict = @{NSFontAttributeName:font};
    CGRect rect = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];

    return rect.size;
}

#pragma mark - 设置文字
- (void)setText:(NSString *)text{
    [super setText:text];
    [self setTextViewDraw];
    if (self.limitLength <= 0) {
        return;
    }
    if ([self.customDelegate respondsToSelector:@selector(textView:count:limitLength:)]) {
        [self.customDelegate textView:self count:self.text.length limitLength:self.limitLength];
    }
}

#pragma mark - 设置提示框
- (void)setPlaceholder:(NSString *)placeholder{
    _placeholder = placeholder;
    _tempPlaceholder = placeholder;
    [self setTextViewDraw];
}

@end
